package api

import (
	"common"
	"common/biz"
	"common/config"
	"common/logs"
	"common/rpc"
	"context"
	"framework/msError"
	"github.com/gin-gonic/gin"
	"net/http"
	"user/pb"
)

type UserHandler struct {
}

func NewUserHandler() *UserHandler {
	return &UserHandler{}
}

func (u *UserHandler) Register(c *gin.Context) {
	//接收参数
	var req pb.RegisterParams
	err2 := c.ShouldBindJSON(&req)
	if err2 != nil {
		common.Fail(c, biz.RequestDataError)
		return
	}
	response, err := rpc.UserClient.Register(context.TODO(), &req)
	if err != nil {
		common.Fail(c, msError.ToError(err))
		return
	}
	uid := response.Uid
	if len(uid) == 0 {
		common.Fail(c, biz.InvalidUsers)
		return
	}
	logs.Info("uid:%s", uid)
	common.Success(c, map[string]any{
		"token":  response.Token,
		"roleID": response.RoleID,
		"serverInfo": map[string]any{
			"host": config.Conf.Services["connector"].ClientHost,
			"port": config.Conf.Services["connector"].ClientPort,
		},
	})

}

func (u *UserHandler) SendSms(c *gin.Context) {
	var req pb.SendSmsParams
	err2 := c.ShouldBindJSON(&req)
	if err2 != nil {
		common.Fail(c, biz.RequestDataError)
		return
	}
	_, err := rpc.SmsClient.Register(context.TODO(), &req)
	if err != nil {
		common.Fail(c, msError.ToError(err))
		return
	}
	common.Success(c, nil)
}

func (u *UserHandler) CallbackPay(c *gin.Context) {
	var req pb.CallbackPayParams
	err2 := c.ShouldBindJSON(&req)
	if err2 != nil {
		common.Fail(c, biz.RequestDataError)
		return
	}
	_, err := rpc.PayClient.Register(context.TODO(), &req)
	if err != nil {
		common.Fail(c, msError.ToError(err))
		return
	}
	common.Success(c, nil)
}

func (u *UserHandler) AlipayCallbackPay(c *gin.Context) {
	// 解析请求参数
	if err := c.Request.ParseForm(); err != nil {
		logs.Warn("解析请求参数发生错误 ,err%v", err)
		return
	}
	var req pb.AlipayCallbackPayParams
	req.CheckValue = c.Request.Form.Encode()
	_, err := rpc.AliPayClient.Register(context.TODO(), &req)
	if err != nil {
		common.Fail(c, msError.ToError(err))
		return
	}
	c.JSON(http.StatusOK, "success")
	//common.Success(c, "success")
}

func (u *UserHandler) GetNotice(c *gin.Context) {
	var req pb.GetNoticeParams
	err2 := c.ShouldBindJSON(&req)
	if err2 != nil {
		common.Fail(c, biz.RequestDataError)
		return
	}
	response, err := rpc.NoticeClient.Register(context.TODO(), &req)
	if err != nil {
		common.Fail(c, msError.ToError(err))
		return
	}
	common.Success(c, map[string]any{
		"title":   response.Title,
		"content": response.Content,
	})
}

func (u *UserHandler) ForgetPassword(c *gin.Context) {
	var req pb.ForgetPasswordParams
	err2 := c.ShouldBindJSON(&req)
	if err2 != nil {
		common.Fail(c, biz.RequestDataError)
		return
	}
	_, err := rpc.ForgetClient.Register(context.TODO(), &req)
	if err != nil {
		common.Fail(c, msError.ToError(err))
		return
	}
	common.Success(c, nil)
}
